﻿using PmSadis.Repositories.Abstract;
using PmSadis.Repositories;
using System.Linq;
using System;
using PmSadis.WebFormsUi.ExpandedControls;
using System.Web.Security;
using System.Linq.Expressions;
using System.Collections.Generic;
using WebMatrix.WebData;
using DevExpress.Web.ASPxGridLookup;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Data;
using DevExpress.Web.ASPxEditors;

namespace PmSadis.WebFormsUi.Administrator
{
    public partial class Users : System.Web.UI.Page
    {
        /// <summary>
        /// Роли пользователя при сохранении
        /// </summary>
        protected static string UserRoles { get; set; }

        /// <summary>
        /// Применяем настройки по-умолчанию для грида
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            gvUsers.SetDefaultSettings();
        }

        /// <summary>
        /// Репозиторий для пользователей
        /// </summary>
        private SadisUserRepository _repo;

        public Users()
        {
            _repo = new SadisUserRepository();
        }

        /// <summary>
        /// Получить всеx пользователей
        /// </summary>
        /// <returns></returns>
        public IQueryable<PmSadis.Models.SadisUserForAdmin> GetAll()
        {
            return _repo.All.Select(x => new PmSadis.Models.SadisUserForAdmin
            {
                UserId = x.UserId,
                UserName = x.UserName,
                DateCreate = x.DateCreate,
                DateUpdate = x.DateUpdate,
                DisplayName = x.DisplayName
            });
        }

        /// <summary>
        /// Все роли
        /// </summary>
        /// <returns></returns>
        public IQueryable GetAllRoles()
        {
            return _repo.AllRoles.Select(x => new
            {
                Role = x,
                RoleName = x
            })
            .AsQueryable();
        }

        /*delete user*/
        /// <summary>
        /// Удалить пользователя
        /// </summary>
        /// <param name="userId">Идентификатор пользователя</param>
        public void DeleteUser(int userId)
        {
            _repo.Delete(userId);
        }

        /*insert user*/
        protected void gvUsers_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;
            var rolesLookup = grid.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["Roles"], "userRoles") as ASPxGridLookup;
            UserRoles = rolesLookup.Text;
        }
        /// <summary>
        /// Добавить пользователя
        /// </summary>
        /// <param name="userName">Логин пользователя</param>
        /// <param name="password">Пароль пользователя</param>
        /// <param name="displayName">Имя для отображения</param>
        /// <returns></returns>
        public int InsertUser(string userName, string password, string displayName)
        {
            var user = new PmSadis.Models.SadisUser
            {
                UserId = 0,
                UserName = userName,
                DisplayName = displayName
            };
            var roles = UserRoles.Split(';').ToList();

            return (int)(_repo as SadisUserRepository).Edit(user, password, roles);
        }


        protected void userRoles_DataBinding(object sender, EventArgs e)
        {
            if (gvUsers.IsNewRowEditing) return;

            var grid = sender as ASPxGridLookup;
            var userName = gvUsers.GetRowValues(gvUsers.EditingRowVisibleIndex, "UserName").ToString();

            var roles = Roles.GetRolesForUser(userName).ToList();

            if (roles.Count != 0)
            {
                var strRoles = string.Empty;
                roles.ForEach(x =>
                {
                    strRoles += string.Format(";{0}", x);
                });

                var rolesLookup = gvUsers.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["Roles"], "userRoles") as ASPxGridLookup;
                rolesLookup.Text = strRoles.Substring(1);
            }
        }

        /*update user*/
        protected void gvUsers_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;
            var rolesLookup = grid.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["Roles"], "userRoles") as ASPxGridLookup;
            UserRoles = rolesLookup.Text;

            var dateCreate = grid.GetRowValues(grid.EditingRowVisibleIndex, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;
        }
        /// <summary>
        /// Обновить пользователя
        /// </summary>
        /// <param name="userId">Идентификатор пользователя</param>
        /// <param name="userName">Логин пользователя</param>
        /// <param name="dateCreate">Дата создания</param>
        /// <param name="displayName">Имя для отображения</param>
        /// <returns></returns>
        public int UpdateUser(int userId, string userName, DateTime dateCreate, string password, string displayName)
        {
            var user = new PmSadis.Models.SadisUser
            {
                UserId = userId,
                UserName = userName,
                DateCreate = dateCreate,
                DisplayName = displayName
            };
            var roles = string.IsNullOrEmpty(UserRoles) ? null : UserRoles.Split(';').ToList();

            return (int)(_repo as SadisUserRepository).Edit(user, password, roles);
        }
    }
}